 package webprog;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import de.fhwgt.quiz.application.Player;
import de.fhwgt.quiz.application.Quiz;

public class HighscoreAktualiesieren {



	public HighscoreAktualiesieren(HttpServletResponse response)throws ServletException, IOException 
	{
		Quiz quiz = Quiz.getInstance();  
		Collection <Player> playersCollection;
		List <Player> playersList;
		PrintWriter writer = response.getWriter(); 
		System.out.println("HighscoreAkutalisieren");
		 
		while(true)
		{
			quiz.waitPlayerChange();
			playersCollection = quiz.getPlayerList(); 
			playersList = new ArrayList <Player> (playersCollection);
			
			Comparator<Player> comp = new PlayerComperator();
			Collections.sort(playersList, comp);
			
			for(Player elem: playersList)
			{ 
				writer.write("event: PlayerChange\n");  
				writer.write("data: " + elem.getName() + "\n");
				writer.write("data: " + elem.getScore() + "\n");  
				writer.write("data: " + elem.getId() + "\n");
			}
			
			writer.write("data: 0\n\n");
			writer.flush();
		}
	}
}
